/*
 * Copyright (C) 2012 Damien Girard <dgirard@nativesoft.fr>
 * Copyright (C) 2012 Sebastien Baudrand <sebbaudrand@gmail.com>
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */
package fr.umlv.qroxy.rules;

import java.io.File;
import java.util.ArrayList;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 *  Check if an Http header is correct or not
 * 
 * @author Damien Girard <dgirard@nativesoft.fr>
 * @author Sebastien BAUDRAND <sebbaudrand@gmail.com>
 */

public class RuleChecker {

    private ArrayList<Rule> rules;

    public RuleChecker() {
        this.rules = new ArrayList<Rule>();
    }

    /**
     * Test an http header. You can pass an http header an return the rule if it
     * exist.
     *
     * @param headerHttp
     * @return Rule
     */
    public Rule RulelookUp(HeaderHttp headerHttp) {
        for (Rule ruleTmp : rules) {
            Matcher m;
            if (headerHttp.getUrlToCall() != null) {
                m = ruleTmp.getUrlPattern().matcher(headerHttp.getUrlToCall());

                if (!m.matches()) {
                    continue; // Invalid rule.
                }
            }

            boolean validRule = true;
            for (Map.Entry<String, Pattern> entry : ruleTmp.getHttpHeaders().entrySet()) {
                String str = headerHttp.getProperties().get(entry.getKey());
                if (str == null) {
                    break;
                }

                m = entry.getValue().matcher(str);
                if (m.matches()) {
                    validRule = false;
                    break;
                }
            }
            if (validRule == false) {
                continue;
            } else {
                return ruleTmp;
            }
        }
        return null;
    }

    public void addRuleFile(File f) throws Exception {
        rules.addAll(Rule.createRulesFromFile(f));
    }

    public ArrayList<Rule> getRules() {
        return rules;
    }
}
